package beans;

import entities.JeuVideo;
import entities.LigneDePanier;
import entities.Panier;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class CartLineFacade extends AbstractFacade<LigneDePanier> {

    @PersistenceContext(unitName = "ProjetAppliWebPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public CartLineFacade() {
        super(LigneDePanier.class);
    }

    public LigneDePanier getByUserCart(Panier cart, JeuVideo videoGame) {
        Query query = em.createQuery("SELECT lp FROM Panier p, IN(p.ligneDePanier) lp WHERE p.id = :panierId AND lp.jeuVideo.id = :jeuVideoId");
        query.setParameter("panierId", cart.getId());
        query.setParameter("jeuVideoId", videoGame.getId());

        try {
            return (LigneDePanier) query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public void updateQuantity(LigneDePanier cartLine) {
        cartLine.setQuantite(cartLine.getQuantite() + 1);
        edit(cartLine);
    }

    public void updateQuantity(LigneDePanier cartLine, int quantity) {
        cartLine.setQuantite(quantity);
        edit(cartLine);
    }
}
